import * as THREE from 'three';
import * as CANNON from "cannon-es";
// import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'
const model = new THREE.Group();
// 物理小球
const sphereMaterial = new CANNON.Material()
const bodyShape = new CANNON.Sphere(0.02);
const body = new CANNON.Body({
    mass: 0.03,
     // 碰撞体的三维空间中位置
    position: new CANNON.Vec3(0, 1, 0),
    shape: bodyShape,
    material:sphereMaterial//碰撞体材质
});
//物理环境
const world = new CANNON.World()
world.gravity.y = -9.8
// 物理地面
const groundMaterial = new CANNON.Material()
const groundBody = new CANNON.Body({
    mass: 0, // 质量为0，始终保持静止，不会受到力碰撞或加速度影响
    shape: new CANNON.Plane(),
    material: groundMaterial,
});
const contactMaterial = new CANNON.ContactMaterial(groundMaterial, sphereMaterial, {
    restitution: 0.4, //反弹恢复系数
})// 把关联的材质添加到物理世界中
world.addContactMaterial(contactMaterial)
// 改变平面默认的方向，法线默认沿着z轴，旋转到平面向上朝着y方向
groundBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0);//旋转规律类似threejs 平面
// world.addBody(body);
world.addBody(groundBody);





// 网格小球
const geometry = new THREE.SphereGeometry( 0.02 );
const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } )
const sphere = new THREE.Mesh( geometry, material );
// 网格地面
const planeGeometry  = new THREE.PlaneGeometry( 200, 200 );
//纹理贴图加载器TextureLoader
const texLoader = new THREE.TextureLoader();
const texture = texLoader.load(require('./瓷砖.jpg'))
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set(3, 3);
const planeMaterial  = new THREE.MeshLambertMaterial({
    // 设置纹理贴图：Texture对象作为材质map属性的属性值
    map: texture,//map表示材质的颜色贴图属性
    side: THREE.DoubleSide
}); 
const planeMesh  = new THREE.Mesh(planeGeometry,planeMaterial);
planeMesh.rotateX(-Math.PI / 2);

const audio = new Audio('/shengyin.mp3');
body.addEventListener('collide', (event) => {
    console.log('碰撞碰撞信息', event.contact);
    audio.pause() 
    if(audio.paused  || audio.ended){
        audio.currentTime = 0
        audio.volume = 1;
        audio.play()
    }
    
})
function render(){
    // console.log('小球的位置',body.position);
    // console.log('小球的速度',body.velocity);
    if(sphere.position.y >-80){
        sphere.position.copy( body.position)
    }
    world.step(1/60)
    requestAnimationFrame(render)
}
render()
model.add(sphere,planeMesh)
export default {model,body,world,audio}; 